package com.jianyun.jyzs.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.EngineerAttach;
import com.jianyun.jyzs.bean.User;
import com.jianyun.jyzs.common.ITextWatchListener;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.dao.EngineerDao;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.AsyTask.AsyncTaskActUtil;
import com.jianyun.jyzs.http.AsyTask.HttpResultActVO;
import com.jianyun.jyzs.http.FileRequestBody;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.presenter.CreateEngineerPresenter;
import com.jianyun.jyzs.utils.EngineerCreateHelper;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.PhotoUtils;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.ICreateEngineerView;
import com.jianyun.jyzs.widget.EngineerAttDialog;
import com.jianyun.jyzs.widget.EngineerAttachExpandView;
import com.jianyun.jyzs.widget.LoadingDialog;
import com.jrmf360.rylib.common.util.ToastUtil;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.jianyun.jyzs.utils.RceLog;
import cn.rongcloud.rce.lib.model.StaffInfo;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangshijun on 2018/5/31.
 */

public class CreateEngineerActivity extends MvpActivity<ICreateEngineerView,
        CreateEngineerPresenter> implements ICreateEngineerView {

    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvChecked;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.et_text)
    EditText etText;
    @BindView(R.id.rce_ll_engineer_attachment)
    RecyclerView rceLlEngineerAttachment;
    @BindView(R.id.iv_project)
    ImageView ivProject;
    @BindView(R.id.tv_project)
    public TextView tvProject;
    @BindView(R.id.ll_project)
    LinearLayout llProject;
    @BindView(R.id.iv_place)
    ImageView ivPlace;
    @BindView(R.id.tv_place)
    public TextView tvPlace;
    @BindView(R.id.ll_place)
    LinearLayout llPlace;
    @BindView(R.id.iv_type)
    ImageView ivType;
    @BindView(R.id.tv_type)
    public TextView tvType;
    @BindView(R.id.ll_type)
    LinearLayout llType;
    @BindView(R.id.iv_look)
    ImageView ivLook;
    @BindView(R.id.tv_look)
    public TextView tvLook;
    @BindView(R.id.ll_look)
    LinearLayout llLook;

    public String projectId = null;//用来保存工程项目的ID 且为null时 项目部位不可选择
    public List<String[]> params;
    private List<String[]> fileValues;
    private EngineerDao dao;
    private LoadingDialog dialog;
    public ArrayList<User> staffInfoArrayList = new ArrayList<>();
    public EngineerAttachExpandView attachExpandView;
    public File cameraFile;//用来保存相机图片
    private String userId;
    private String enterpriseCode;
    private String name;
    private EngineerCreateHelper createHelper;
    private HashMap<String, RequestBody> mParamsHasmap;
    //private CreateEngineerUtils createEngineerUtils;
    //HashMap<String, RequestBody> map = new HashMap<>();
    //map.put("enterpriseCode", RequestBody.create(MediaType.parse("text/plain"),enterpriseCode));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_create_engineer);
           ButterKnife.bind(this);
        initData();
        initView();
    }

    private void initData() {
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        name = LoginCache.getInstance().getUserDetaileInfo().getName();
        // createEngineerUtils = new CreateEngineerUtils(this);
        createHelper = new EngineerCreateHelper(this);
        params = new ArrayList<String[]>();
        mParamsHasmap = new HashMap<>();
        fileValues = new ArrayList<String[]>();
        dao = new EngineerDao(this);
        dialog = LoadingDialog.create(this);
        dialog.setCancellable(false);
    }

    private void initView() {
        topBack.setVisibility(View.VISIBLE);
        tvChecked.setVisibility(View.VISIBLE);
        topText.setVisibility(View.VISIBLE);
        topText.setText("创建工程动态");
        tvChecked.setText("创建");
        tvChecked.setTextColor(getResources().getColor(R.color.blue));
        setAttachView();
        initTextListener();
    }

    private void setAttachView() {
        List<EngineerAttach> list = new ArrayList<>();
        attachExpandView = EngineerAttachExpandView.init(this, rceLlEngineerAttachment, list);
        attachExpandView.setListener(new EngineerAttDialog.OnDialogItemClickListener() {
            @Override
            public void onItemClick(int index) {
                switch (index) {
                    case 0:
                        new PhotoUtils().selectPicture2(CreateEngineerActivity.this);
                        break;
                    case 1:
                        createHelper.openCameraWithPermission();
                        break;
                    case 2:
                        startActivityForResult(new Intent(CreateEngineerActivity.this, EngineerRecordActivity.class), 100);
                        break;
                    case 3:
                        createHelper.openVideoWithPermission();
                        break;
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            createHelper.onActivityResult(requestCode, resultCode, data);
        }
    }

    @NonNull
    @Override
    public CreateEngineerPresenter createPresenter() {
        return new CreateEngineerPresenter();
    }

    @OnClick({R.id.topBack, R.id.tv_checked, R.id.ll_project, R.id.ll_place, R.id.ll_type, R.id.ll_look})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topBack:
                finish();
                break;
            case R.id.tv_checked:
                //initCreateArgs();//设置请求参数
                try {
                    asySend();//开始创建工程动态
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.ll_project:
                startActivityForResult(new Intent(this, EngineerProjectActivity.class), 110);

                break;
            case R.id.ll_place:
                if (projectId == null) {
                    ToastUtil.showNoWaitToast(this, "请先选择一个工程项目");
                } else {
                    startActivityForResult(new Intent(this, EngineerLocationActivity.class).putExtra(SysConstant.msg_key_string1, projectId), 120);
                }
                break;
            case R.id.ll_type:
                startActivityForResult(new Intent(this, EngineerTypeActivity.class), 130);

                break;
            case R.id.ll_look:

                startActivityForResult(new Intent(this, EngineerLookActivity.class), 140);


                break;
        }
    }

    private void asySend() throws Exception {

        String ENCODE = "utf-8";
        String description = etText.getText().toString().trim();
        if (TextUtils.isEmpty(description)) {
            ToastUtil.showNoWaitToast(this, "动态描述不可为null");
            return;
        }
        String tvproject = tvProject.getText().toString().trim();
        if (TextUtils.isEmpty(tvproject)) {
            ToastUtil.showNoWaitToast(this, "请选择一个项目");
            return;
        } else {
            mParamsHasmap.put("projectId", RequestBody.create(MediaType.parse("text/plain"), projectId));
            mParamsHasmap.put("projectName", RequestBody.create(MediaType.parse("text/plain"), URLEncoder.encode(tvproject, ENCODE)));
        }
        String placetext = tvPlace.getText().toString().trim();
        if (!TextUtils.isEmpty(placetext)) {
            mParamsHasmap.put("place", RequestBody.create(MediaType.parse("text/plain"), URLEncoder.encode(placetext, ENCODE)));

        }
        String typetext = tvType.getText().toString().trim();
        if (!TextUtils.isEmpty(typetext)) {
            mParamsHasmap.put("type", RequestBody.create(MediaType.parse("text/plain"), URLEncoder.encode(typetext, ENCODE)));
        }
        //增加可看联系人
        String userIds = "";
        if (staffInfoArrayList.size() > 0) {
            for (User sa : staffInfoArrayList) {
                userIds = userIds + sa.getServerUserId() + ",";
            }
        }
        mParamsHasmap.put("method", RequestBody.create(MediaType.parse("text/plain"), "SendProjectProgress"));
        mParamsHasmap.put("userId", RequestBody.create(MediaType.parse("text/plain"), userId));
        mParamsHasmap.put("userName", RequestBody.create(MediaType.parse("text/plain"), URLEncoder.encode(name, ENCODE) + ","));
        mParamsHasmap.put("enterpriseCode", RequestBody.create(MediaType.parse("text/plain"), enterpriseCode));
        mParamsHasmap.put("text", RequestBody.create(MediaType.parse("text/plain"), URLEncoder.encode(description, ENCODE)));
        mParamsHasmap.put("position", RequestBody.create(MediaType.parse("text/plain"), "position"));
        //增加可看联系人
        mParamsHasmap.put("userIds", RequestBody.create(MediaType.parse("text/plain"), userIds));

        mParamsHasmap.put("appCode", RequestBody.create(MediaType.parse("text/plain"), "jyzs"));
        mParamsHasmap.put("appType", RequestBody.create(MediaType.parse("text/plain"), "Android"));
        mParamsHasmap.put("appVersion", RequestBody.create(MediaType.parse("text/plain"), "1.0.2"));


        List<EngineerAttach> attachList = attachExpandView.getAttachList();
        if (attachList.size() == 0) {
            ToastUtil.showNoWaitToast(this, "请至少选择一个附件");
            return;
        }
        String fileExtName = "";
        String fileType = "";
        String duration = "";
        for (EngineerAttach ea : attachList) {
            fileExtName = fileExtName + "." + ea.getName() + ",";
            fileType = fileType + ea.getCategory() + ",";
            if (ea.getCategory() == 1) {
                duration = duration + "0" + ",";
            } else if (ea.getCategory() == 2) {
                duration = duration + "10" + ",";
            } else if (ea.getCategory() == 3) {
                duration = duration + "10" + ",";

            }
            fileValues.add(new String[]{ea.getName(), ea.getPath2()});
        }

        MultipartBody.Part[] parts = new MultipartBody.Part[fileValues.size()];
        if (fileValues != null) {
            for (int i = 0; i < fileValues.size(); i++) {
                String[] str = fileValues.get(i);
                File file = new File(str[1]);
                String s = str[0];
                MultipartBody.Part part = MultipartBody.Part.createFormData("file", s, new FileRequestBody(file, null));
                parts[i] = part;
            }

        }


        MediaType textType = MediaType.parse("text/plain");
        RequestBody filename = RequestBody.create(textType, fileExtName);
        RequestBody type = RequestBody.create(textType, fileType);
        RequestBody dur = RequestBody.create(textType, duration);
        dialog.show();

        Api api = RetrofitHelper.builderErpRoot2().create(Api.class);
        api.createNewEngineer(mParamsHasmap, filename, type, dur, parts)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        dialog.dismiss();
                    }

                    @Override
                    public void onNext(Object o) {

                        String json = new Gson().toJson(o);
                        Log.i("test", "创建成功：" + json.toString());
                        try {
                            JSONObject jsonObject = new JSONObject(json);
                            boolean aBoolean = jsonObject.getBoolean("result");
                            if (aBoolean) {
                                String id = jsonObject.getString("id");
                                //得到创建成功的ID 去获取工程动态详情保存到数据库
                                HashMap<String, String> map = new HashMap<>();
                                map.put("method", "GeProjectProgressByProjectProgressId");
                                map.put("enterpriseCode", enterpriseCode);
                                map.put("userId", userId);
                                map.put("progressId", id);
                                map.put("appCode", "jyzs");
                                map.put("appType", "Android");
                                map.put("appVersion", "1.0.2");
                                //创建成功后获取单个项目动态
                                getPresenter().getOneEngineer(dao, map);

                            } else {
                                String message = jsonObject.getString("message");
                                ToastUtil.showNoWaitToast(CreateEngineerActivity.this, message);
                                dialog.dismiss();
                            }

                            RceLog.d("lml", jsonObject.toString());
                        } catch (JSONException e) {
                            dialog.dismiss();
                            e.printStackTrace();
                            ToastUtil.showNoWaitToast(CreateEngineerActivity.this, e.getMessage());
                        }

                    }
                });
    }


    private static MultipartEntity processSendData(List<String[]> params, List<String[]> fileValues) {
        MultipartEntity mpEntity = new MultipartEntity();
        if (params != null) {
            for (String[] str : params) {
                try {
                    mpEntity.addPart(str[0], new StringBody(str[1] == null ? "" : str[1], Charset.forName("UTF-8")));
                } catch (Exception e) {
                }
            }
        }
        if (fileValues != null) {
            for (String[] str : fileValues) {
                mpEntity.addPart(str[0], new FileBody(new File(str[1])));
            }
        }
        return mpEntity;
    }

    private void initTextListener() {
        tvProject.addTextChangedListener(new ITextWatchListener() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String pstr = s.toString();
                if (!TextUtils.isEmpty(pstr)) {
                    ivProject.setImageResource(R.drawable.gongchengdongtaic_icon_xiangmu_pressed);
                } else {
                    ivProject.setImageResource(R.drawable.gongchengdongtaic_icon_xiangmu_default);
                }
            }
        });
        tvPlace.addTextChangedListener(new ITextWatchListener() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String pstr = s.toString();
                if (!TextUtils.isEmpty(pstr)) {
                    ivPlace.setImageResource(R.drawable.gongchengdongtaic_icon_buwei_pressed);
                } else {
                    ivPlace.setImageResource(R.drawable.gongchengdongtaic_icon_buwei_default);
                }
            }
        });
        tvType.addTextChangedListener(new ITextWatchListener() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String pstr = s.toString();
                if (!TextUtils.isEmpty(pstr)) {
                    ivType.setImageResource(R.drawable.gongchengdongtaic_icon_leixing_pressed);
                } else {
                    ivType.setImageResource(R.drawable.gongchengdongtaic_icon_leixing_default);
                }
            }
        });
        tvLook.addTextChangedListener(new ITextWatchListener() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String pstr = s.toString();
                if (pstr.equals("部分可见")) {
                    ivLook.setImageResource(R.drawable.gongchengdongtaic_icon_chakan_pressed);
                } else {
                    ivLook.setImageResource(R.drawable.gongchengdongtaic_icon_chakan_default);
                }
            }
        });
    }

    @Override
    public void onGetEngineerSuccess() {
        setResult(-1);
        finish();

    }

    @Override
    public void onFailed(String msg) {
        ToastUtil.showNoWaitToast(this, msg);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hintLoading() {
        dialog.dismiss();
    }



}
